﻿using System;
using System.IO;
using System.Xml;
using System.Configuration;
using System.Web;
using SyCODE.Component.DataFactory;
using System.Collections.Specialized;
using SyCODE.Component.Security;
using SyCODE.Component.Cryptography;
using SyCODE.Component;
using System.Text;
using System.Web.Security;

/// <summary>
/// SyCODE 的摘要说明
/// </summary>
namespace SyCODE.Blog
{
    public class SetUserInfo : IHttpHandler
    {
        public bool IsReusable
        {
            get { return true; }
        }

        private void WriteDocHead(XmlTextWriter writer, NameValueCollection nvc)
        {
            writer.WriteStartElement("head");

            writer.WriteStartElement("meta");
            writer.WriteAttributeString("http-equiv", "Content-Type");
            writer.WriteAttributeString("content", "text/html; charset=utf-8");
            writer.WriteEndElement();

            writer.WriteStartElement("title");
            writer.WriteString(String.Format(StringResource.GetField("infotitle"), nvc["n"]) + " - Powered By X3BLOG");
            writer.WriteEndElement();

            writer.WriteEndElement();
        }

        private void WriteTitleNode(XmlTextWriter writer, string name)
        {
            writer.WriteStartElement("span");
            writer.WriteString(StringResource.GetField("info_" + name));
            writer.WriteEndElement();
        }

        private void WriteFieldNode(XmlTextWriter writer, string name, string value)
        {
            writer.WriteStartElement("p");

            writer.WriteAttributeString("id", name);

            WriteTitleNode(writer, name);

            writer.WriteStartElement("span");
            writer.WriteString(value);
            writer.WriteEndElement();

            writer.WriteEndElement();
        }

        private void WriteFieldNode(XmlTextWriter writer, string name, string key, string value)
        {
            writer.WriteStartElement("p");

            writer.WriteAttributeString("id", name);

            WriteTitleNode(writer, name);

            writer.WriteStartElement("span");
            writer.WriteAttributeString("title", value);
            writer.WriteString(ConstData.Get(key, value).Value);
            writer.WriteEndElement();

            writer.WriteEndElement();
        }

        private void WriteFieldNode(XmlTextWriter writer, string name, string key, string value, string value2)
        {
            writer.WriteStartElement("p");

            writer.WriteAttributeString("id", name);

            WriteTitleNode(writer, name);

            writer.WriteStartElement("span");
            writer.WriteAttributeString("title", value);
            writer.WriteString(ConstData.Get(key, value).Value);
            writer.WriteEndElement();

            writer.WriteStartElement("span");
            writer.WriteAttributeString("title", value2);
            writer.WriteString(ConstData.Get(key, value, value2).Value);
            writer.WriteEndElement();

            writer.WriteEndElement();
        }

        private void WriteFieldNode(XmlTextWriter writer, string name, string key, string[] value, string value2)
        {
            writer.WriteStartElement("p");

            writer.WriteAttributeString("id", name);

            WriteTitleNode(writer, name);

            StringBuilder sbValue = new StringBuilder();
            for (int i = 0; i < value.Length; i++)
            {
                if (i > 0)
                {
                    sbValue.Append(",");
                }
                sbValue.Append(ConstData.Get(key, value[i]).Value);
            }

            writer.WriteStartElement("span");
            writer.WriteAttributeString("title", String.Join(",", value));
            writer.WriteString(sbValue.ToString());
            writer.WriteEndElement();

            writer.WriteStartElement("span");
            writer.WriteString(value2);
            writer.WriteEndElement();

            writer.WriteEndElement();
        }

        private void WriteDocBody(XmlTextWriter writer, NameValueCollection nvc)
        {
            writer.WriteStartElement("body");

            WriteFieldNode(writer, "realname", nvc["realname"]);
            WriteFieldNode(writer, "gender", "gender", nvc["gender"]);
            WriteFieldNode(writer, "birthday", nvc["year"] + "/" + nvc["month"] + "/" + nvc["day"]);
            WriteFieldNode(writer, "birthday2", nvc["birthday"]);
            WriteFieldNode(writer, "aniproto", nvc["aniproto"]);
            WriteFieldNode(writer, "constellation", nvc["constellation"]);
            WriteFieldNode(writer, "people", "people", nvc["people"]);
            WriteFieldNode(writer, "oprovince", "province", nvc["oprovince"], nvc["ocity"]);
            WriteFieldNode(writer, "province", "province", nvc["province"], nvc["city"]);
            WriteFieldNode(writer, "resume", nvc["resume"]);
            WriteFieldNode(writer, "height", nvc["height"]);
            WriteFieldNode(writer, "weight", nvc["weight"]);
            WriteFieldNode(writer, "blood", "blood", nvc["blood"]);
            WriteFieldNode(writer, "marital", "marital", nvc["marital"]);
            WriteFieldNode(writer, "smoke", "smoke", nvc["smoke"]);
            WriteFieldNode(writer, "drink", "drink", nvc["drink"]);
            WriteFieldNode(writer, "industry", "industry", nvc["industry"], nvc["occupation"]);
            WriteFieldNode(writer, "salary", "salary", nvc["salary"]);
            WriteFieldNode(writer, "knowledge", "knowledge", nvc["knowledge"]);
            WriteFieldNode(writer, "school", nvc["school"]);
            WriteFieldNode(writer, "speciality", nvc["speciality"]);
            WriteFieldNode(writer, "character", "character", String.IsNullOrEmpty(nvc["character"]) ? new string[] { } : nvc["character"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries), nvc["other_character"]);
            WriteFieldNode(writer, "hobby", "hobby", String.IsNullOrEmpty(nvc["hobby"]) ? new string[] { } : nvc["hobby"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries), nvc["other_hobby"]);
            WriteFieldNode(writer, "sport", nvc["sport"]);
            WriteFieldNode(writer, "book", nvc["book"]);
            WriteFieldNode(writer, "music", nvc["music"]);
            WriteFieldNode(writer, "movie", nvc["movie"]);
            WriteFieldNode(writer, "star", nvc["star"]);
            WriteFieldNode(writer, "address", nvc["address"]);
            WriteFieldNode(writer, "postcode", nvc["postcode"]);
            WriteFieldNode(writer, "phone", nvc["phone"]);
            WriteFieldNode(writer, "email", nvc["email"]);
            WriteFieldNode(writer, "msn", nvc["msn"]);
            WriteFieldNode(writer, "qq", nvc["qq"]);
            WriteFieldNode(writer, "skype", nvc["skype"]);
            WriteFieldNode(writer, "contact", nvc["contact"]);

            writer.WriteEndElement();
        }

        private void SaveUserDetailInfo(NameValueCollection nvc)
        {
            XmlTextWriter writer = null ;
            try
            {
                writer = new XmlTextWriter(File.Open(Path.Combine(AppPath.GetUserPhysicalPath(nvc["u"]), "info.xml"), FileMode.Truncate), Encoding.UTF8);
                writer.WriteStartDocument();
                writer.WriteProcessingInstruction("xml-stylesheet", "type='text/xsl' href='/ui/common/info.xsl'");
                writer.WriteStartElement("html");

                this.WriteDocHead(writer, nvc);

                this.WriteDocBody(writer, nvc);

                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Flush();
            }
            finally
            {
                writer.Close();
            }
        }

        public void ProcessRequest(HttpContext context)
        {
			Ticket ticket = Ticket.Get(FormsAuthentication.FormsCookieName);
            if (Ticket.Authenticate(ticket))
            {
                NameValueCollection nvc;
                DBAM dbam;

                switch (context.Request.Form["active"])
                {
                    case "0":
                        nvc = new NameValueCollection();
                        nvc.Add("u", ticket.Name);
                        nvc.Add("n", HttpUtility.HtmlDecode(ticket.UserData));
                        nvc.Add("old", SHA1.Encrypt(context.Request.Form["oldpwd"]));
                        nvc.Add("pwd", SHA1.Encrypt(context.Request.Form["newpwd"]));

                        dbam = new DBAM();
                        try
                        {
                            dbam.BuildParameters("setuserpwd", nvc);
                            if (dbam.Execute() == 0)
                            {
                                Function.ClientAlert(StringResource.GetField("invalidoldpassword"));
                            }
                        }
                        finally
                        {
                            dbam.Dispose();
                        }
                        break;
                    case "1":
                        Updater.HeadInfo updater = new SyCODE.Blog.Updater.HeadInfo(ticket.Name);
                        updater.SetUserInfo(context.Request.Form["name"], context.Request.Form["email"]);
                        updater.Dispose();
                        break;
                    case "2":
                        nvc = new NameValueCollection(context.Request.Form);
                        nvc.Add("u", ticket.Name);

                        dbam = new DBAM();
                        try
                        {
                            dbam.BuildParameters("setuserdetail", nvc);
                            if (dbam.Execute() > 0)
                            {
                                this.SaveUserDetailInfo(nvc);
                            }
                            else
                            {
                                Function.ClientAlert(StringResource.GetField("unkownexception"));
                            }
                        }
                        finally
                        {
                            dbam.Dispose();
                        }
                        break;
                }
            }
            else
            {
                Function.ClientAlert(StringResource.GetField("authfaild"));
            }
        }
    }
}